package com.example.esaclient;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;

import android.app.AlertDialog;
import android.app.ListFragment;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public  class TabMentionTimeline extends ListFragment {			
	 
	 View fragView;	  
	  Integer esaUsrID=0;
	  SimpleAdapter adapter;
	  ArrayList<HashMap<String, Object>> data;
	  Boolean LoggedToTwitter=false,LoggedToFacebook=false,LoggedToGoogle=false;
	    // Progress dialog
	    ProgressDialog dialog;
	    
	    //listView
	    ListView lv;
	    int position,top=0;
	    boolean loadingMore=true;
	    static int count,size = 0;
	    int lastPostViewed=0;
	    int oldItemCount=0;
	    static int N_ITEMS_TO_LOAD=5;
	    
	    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
   	 
           View fragView = inflater.inflate(R.layout.tabscontent, container, false);
      
           esaUsrID=new GlobalSettings(this.getActivity()).getPrefInt(GlobalSettings.PREF_ESA_USRID);   
           
           refresh();
            return fragView;
    }
    
    
    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

  	  //View footerView =inflater.inflate(R.layout.footer, null, false);
        //lv.addFooterView(footerView);
  	lv= getListView();
  	
  	lv.setOnItemLongClickListener(new OnItemLongClickListener() {

        public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                int pos, long id) {
            // TODO Auto-generated method stub

          final HashMap<String, Object> elem=data.get(pos);
          AlertDialog.Builder dialog = new AlertDialog.Builder(TabMentionTimeline.this.getActivity());
          dialog.setTitle(elem.get("tagger").toString());
          dialog.setMessage(elem.get("message").toString());
          dialog.setPositiveButton(" Share on Facebook ", new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog, int id) {
                  dialog.dismiss();
                  String msg ="On " + elem.get("time").toString() + ", " + elem.get("tagger").toString() +" shared on"+ elem.get("socialNetwork").toString().replace("Via", "") +": \n \""+elem.get("message").toString()+ "\"";
                  
                  try {
					new CrossPostingFB(TabMentionTimeline.this.getActivity()).execute(esaUsrID,URLEncoder.encode(msg, "utf-8"));
				} catch (UnsupportedEncodingException e) {
				
					e.printStackTrace();
				}

              }
              
          });
          
          dialog.setNegativeButton("Re-tweet", new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog, int id) {
                  dialog.dismiss();
                  String msg =elem.get("tagger").toString() +" shared on"+ elem.get("socialNetwork").toString().replace("Via", "") +":\n"+elem.get("message").toString();
                  //limit to 140 chars
                  msg=msg.substring(0, Math.min(msg.length(), 140));
                  try {
					new CrossPostingTW(TabMentionTimeline.this.getActivity()).execute(esaUsrID,URLEncoder.encode(msg, "utf-8"));
				} catch (UnsupportedEncodingException e) {
				
					e.printStackTrace();
				}
              }
          });
          dialog.show();
     
            return true;
        }
    }); 
      

         this.getListView().setOnScrollListener(new OnScrollListener() {
             @Override
             public void onScrollStateChanged(AbsListView view, int scrollState) {
             }

             @Override
             public void onScroll(AbsListView view, int firstVisibleItem,
                     int visibleItemCount, int totalItemCount) {

                 position = firstVisibleItem;
                 View v = lv.getChildAt(0);
                 top = (v == null) ? 0 : v.getTop();
                 int lastInScreen = firstVisibleItem + visibleItemCount;
                
              
                 if ((lastInScreen == totalItemCount) && !(loadingMore) && (oldItemCount!=totalItemCount)) {
                    
                         try {loadingMore=true;
                         lastPostViewed=lastInScreen;
                      //   System.out.println("Last Before->" +lastPostViewed);
                        	  System.out.println("Calling WS:" + totalItemCount +"->"+(totalItemCount+N_ITEMS_TO_LOAD));
                      		new GetMyTags(TabMentionTimeline.this).execute(esaUsrID, "", totalItemCount+2,totalItemCount+N_ITEMS_TO_LOAD);
                      		oldItemCount=totalItemCount;
                         } catch (Exception e) {
                             e.printStackTrace();
                         }

                 }
             }
         });
         
    
    }

public void refresh() {
		

		//TODO: usare GetServicesOn
	
	
	
	oldItemCount=0;
	
		GlobalSettings gs = new GlobalSettings(this.getActivity());
		LoggedToTwitter = gs.getPrefBool(GlobalSettings.PREF_KEY_TWITTER_LOGIN);
		LoggedToFacebook = gs.getPrefBool(GlobalSettings.PREF_KEY_FACEBOOK_LOGIN);
		LoggedToGoogle = gs.getPrefBool(GlobalSettings.PREF_KEY_GOOGLE_LOGIN);
	
		if(data!=null){
			data.clear();
			adapter.notifyDataSetChanged();}
		
		if (LoggedToFacebook || LoggedToTwitter || LoggedToGoogle){
			loadingMore=true;
			final AsyncTask<Object, Integer, ArrayList<HashMap<String, Object>>> g;
			g=new GetMyTags(this).execute(esaUsrID, "", 0,N_ITEMS_TO_LOAD);
		
			dialog = ProgressDialog.show(this.getActivity(), "", "Contacting Esa Server. Please, Wait...", true,true,new OnCancelListener(){
		        
		        public void onCancel(DialogInterface dialog) {
		            //Check the status, status can be RUNNING, FINISHED and PENDING
		            //It can be only cancelled if it is not in FINISHED state
		            if (g != null && g.getStatus() != AsyncTask.Status.FINISHED){
		                g.cancel(true);
						 System.out.println("Update aborted." +lastPostViewed);
                       
						}
		        }
		    });	
			dialog.show();  
			
		}
		else{
			if(dialog!=null)
			dialog.dismiss();
		}
	}


public void fillList(ArrayList<HashMap<String,Object>> result){
	
	if(data==null)
		data=new ArrayList<HashMap<String,Object>>();
		
	
	data.addAll(result);
	if(data.size() >0){
	String[] from = { "message", "time", "socialNetwork","taggerPicture", 
			"tagger" }; // from values of hashMap
	int[] to = { R.id.lstTAGMessage, R.id.lstTAGtime, R.id.lstTAGFrom,
			 R.id.lstTAGImage, R.id.lstTagger };// to id of view
      
    adapter=new SimpleAdapter(
                   this.getActivity().getApplicationContext(),
                    data,//data source
                    R.layout.feed_tag_element, //layout of a single feed element
                    from,
                    to);
	
 //   ((ListView)this.getActivity().findViewById(R.id.list)).setAdapter(adapter);
    
    lv.setAdapter(adapter);
    adapter.notifyDataSetChanged();
  //  System.out.println("Last After->" +lastPostViewed);
    lv.setSelectionFromTop(position, top);
    
	}
	loadingMore=false;
}



public void ClearList(){
	
	
	ArrayList<HashMap<String, Object>> data=new ArrayList<HashMap<String,Object>>();
	
	
	
	EsaPost e=new EsaPost("");
				 

		data.add(e.feed);	
		
		
	 String[] from={"message","time","socialNetwork","picture","tagger"}; //from values of hashMap
        int[] to={R.id.lstTAGMessage,R.id.lstTAGtime,R.id.lstTAGFrom,R.id.lstTAGImage,R.id.lstTagger};//to id of view
        

    adapter=new SimpleAdapter(
                   this.getActivity().getApplicationContext(),
                    data,//data source
                    R.layout.feed_tag_element, //layout of a single feed element
                    from,
                    to);
	
  //  ((ListView)this.getActivity().findViewById(R.id.list)).setAdapter(adapter);
}


public void GetMyTagsResult(ArrayList<HashMap<String,Object>> result){
	dialog.dismiss();
	fillList( result);
}


}